﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;
using Mani.Common.Security;

namespace Mani.Common.UI
{
    public partial class RolesManager : System.Web.UI.UserControl
    {
        private const String DEFAULT_APPLICATION_ID = "E6ED2728-D5C7-45FC-8183-52A6C624E311";

        public ISecurityManager securityManager { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (!Page.IsPostBack)
            {
                LoadActions();
                LoadApplications();
                LoadRoles();
            }
        }

        private void LoadApplications()
        {
            ddlApplications.DataSource = securityManager.GetApplications();
            ddlApplications.DataBind();
        }

        private void LoadRoles()
        {
            if (ddlApplications.SelectedValue == DEFAULT_APPLICATION_ID)
                gvRoles.DataSource = new List<aspnet_Roles>();
            else
                gvRoles.DataSource = securityManager.GetRolesByApplication(Guid.Parse(ddlApplications.SelectedValue));

            gvRoles.DataBind();
        }

        private void LoadActions()
        {
            if (ddlApplications.SelectedValue == DEFAULT_APPLICATION_ID)
                cbRoleActions.DataSource = new List<Security.Action>();
            else
                cbRoleActions.DataSource = securityManager.GetActionsByApplication(Guid.Parse(ddlApplications.SelectedValue));

            cbRoleActions.DataBind();
        }

        protected void btnSaveChanges_Click(object sender, EventArgs e)
        {
            if (ddlApplications.SelectedValue == DEFAULT_APPLICATION_ID)
            {
                UIHelper.ClientAlert(this.Page, "لطفا ابتدا نام سیستم مورد نظر خود را انتخاب کنید");
                return;
            }

            MembershipProvider provider = Membership.Providers[ddlApplications.SelectedItem.Text];
            if (provider == null)
            {
                UIHelper.ClientAlert(this.Page, "بانک اطلاعاتی سیستم انتخاب شده در فایل وب کانفیگ ثبت نشده است");
                return;
            }

            if (String.IsNullOrEmpty(lblRoleId.Text))
                New();
            else
                Update();

            ClearForm();
            LoadRoles();
            UIHelper.ClientAlert(this.Page, "تغییرات با موفقیت ذخیره شد");
        }

        private void Update()
        {
            aspnet_Roles role = securityManager.GetRoleById(Guid.Parse(lblRoleId.Text));

            foreach (ListItem item in cbRoleActions.Items)
            {
                Mani.Common.Security.Action action = securityManager.GetActionById(Convert.ToInt32(item.Value));

                if (item.Selected)
                {
                    if (role.Actions.Where(a => a.ActionId == Convert.ToInt32(item.Value)).Count() == 0)
                        securityManager.AddActionToRole(action, role);
                }
                else if (role.Actions.Where(a => a.ActionId == Convert.ToInt32(item.Value)).Count() > 0)
                {
                    securityManager.RemoveActionFromRole(action, role);
                }
            }
        }

        private void New()
        {
            aspnet_Roles role = securityManager.CreateRoleInApplication(txtRoleName.Text, ddlApplications.SelectedItem.Text);

            foreach (ListItem item in cbRoleActions.Items)
            {
                if (item.Selected)
                    securityManager.AddActionToRole(securityManager.GetActionById(Convert.ToInt32(item.Value)), role);
            }
        }

        protected void gvRoles_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
        }

        protected void gvRoles_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Guid RoleId = Guid.Parse(gvRoles.DataKeys[e.RowIndex].Value.ToString());

            try
            {
                securityManager.DeleteRoleById(RoleId);
            }
            catch (SqlException ex)
            {
                if (ex.ToString().Contains("The DELETE statement conflicted"))
                    UIHelper.ClientAlert(this.Page, "این نقش دارای کاربر می باشد و قابل حذف نمی باشد");
                else
                    throw;

                return;
            }

            LoadRoles();
            ClearForm();
        }

        protected void gvRoles_RowCreated(object sender, GridViewRowEventArgs e)
        {
            UIHelper.GridDeleteConfirm(e.Row);
        }

        protected void gvRoles_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            ClearForm();

            Guid roleId = Guid.Parse(gvRoles.DataKeys[e.NewSelectedIndex].Value.ToString());
            aspnet_Roles role = securityManager.GetRoleById(roleId);

            lblRoleId.Text = role.RoleId.ToString();
            txtRoleName.Text = role.RoleName;
            txtRoleName.ReadOnly = true;

            foreach (Mani.Common.Security.Action a in role.Actions)
            {
                ListItem item = cbRoleActions.Items.FindByValue(a.ActionId.ToString());
                if (item != null)
                    item.Selected = true;
            }
        }

        private void ClearForm()
        {
            lblRoleId.Text = String.Empty;
            txtRoleName.Text = String.Empty;
            txtRoleName.ReadOnly = false;
            cbRoleActions.ClearSelection();
        }

        protected void ddlApplications_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadRoles();
            LoadActions();
        }
    }
}